package com.heima.user.service.impl;

import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    StringRedisTemplate redisTemplate;  //key  value都是使用字符串序列化
    @Override
    public ResponseResult follow(UserRelationDTO dto) {
        //1.校验参数 (是否登录 判断operation: 0 1)
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //登录用户id
        Integer loginUserId = user.getId();
        //作者用户id
        Integer authorUserId = dto.getAuthorApUserId();
        //2.如果operation为0的话他要执行关注操作
        Short operation = dto.getOperation();
        if (operation.intValue() == 0) {
            //2.1判断登录用户是否已经关注作者
            Double score = redisTemplate.opsForZSet().score(UserRelationConstants.FOLLOW_LIST + loginUserId, String.valueOf(authorUserId));
            if (score!=null) {
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"请勿重复关注");
            }
            //2.2判断登录用户和作者用户是否是同一个用户
            if (loginUserId.equals(authorUserId)) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"请勿自关");
            }
            //2.3在登录用户的集合中 加入作者用户id
            redisTemplate.opsForZSet().add(UserRelationConstants.FOLLOW_LIST+loginUserId,String.valueOf(authorUserId),System.currentTimeMillis());
            //2.4在作者用户的集合中加入登录用户id
            redisTemplate.opsForZSet().add(UserRelationConstants.FANS_LIST+authorUserId,String.valueOf(loginUserId),System.currentTimeMillis());
        } else {
            //3.如果operation为1的话执行取关操作

            //3.1在登录用户的集合中 删除作者用户id
            redisTemplate.opsForZSet().remove(UserRelationConstants.FOLLOW_LIST+loginUserId,String.valueOf(authorUserId));
            //3.2在作者用户的集合中删除登录用户id
            redisTemplate.opsForZSet().remove(UserRelationConstants.FANS_LIST+authorUserId,String.valueOf(loginUserId));
        }
        return ResponseResult.okResult();
    }
}
